<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="showTrademarkDialog"
          >添加</el-button
        >
      </div>

      
    </template>

    <!-- 表格数据 -->
    <el-table
      border
      :data="trademarkList"
      style="width: 100%; margin-bottom: 20px"
      v-loading="loading"
    >
      <el-table-column type="index" label="序号" width="80"> </el-table-column>
      <el-table-column prop="tmName" label="品牌名称" width="180">
      </el-table-column>
      <el-table-column label="品牌logo">
        <template v-slot="{ row }">
          <img :src="row.logoUrl" alt="" style="width: 100px" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template v-slot="{ row }">
          <!-- 编辑品牌功能 -->
          <el-tooltip
            class="box-item"
            effect="dark"
            content="编辑品牌"
            placement="top"
          >
            <el-button
              type="warning"
              size="small"
              icon="el-icon-edit-outline"
              @click="toEditTrademarkInfo(row)"
            />
          </el-tooltip>
          <!-- 删除品牌功能 -->
          <el-tooltip
            class="box-item"
            effect="dark"
            content="删除品牌"
            placement="top"
          >
            <el-button
              type="danger"
              size="small"
              icon="el-icon-delete"
              @click="toRemoveTrademarkInfo(row)"
            />
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <!-- :current-page="currentPage4" -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :page-sizes="[3, 6, 9, 12]"
      :page-size="pageSize"
      :current-page="currentPage"
      layout="  prev, pager, next, jumper,->,sizes,total"
      :total="total"
      style="text-align: center"
    />

    <!-- 弹出来的对话框 -->
    <el-dialog title="添加品牌" :visible.sync="dialogFormVisible">
      <el-form :model="trademarkInfo" :rules="rules" ref="ruleForm">
        <el-form-item label="品牌名称" label-width="100px">
          <el-input
            v-model="trademarkInfo.tmName"
            autocomplete="off"
            style="width: 300px"
            prop="tmName"
          />
        </el-form-item>
        <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            action="/dev-api/admin/product/fileUpload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="trademarkInfo.logoUrl" :src="trademarkInfo.logoUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <template #tip>
              <div class="el-upload__tip">
                只能上传jpg/png等图片格式,且大小不能超过2M
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addTrademark">确 定</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
import { reqAddTrademark, reqEditTrademark } from "@/api/product/trademark";
export default {
  name: "Trademark",

  data() {
    return {
      currentPage: 1, //默认的页码为第一页
      total: 0, //默认的数据总条数为0
      pageSize: 3, //默认每页展示3条数据
      loading: true, //请求数据的加载
      trademarkList: [], //数据列表
      small: false,
      dialogTableVisible: false,
      dialogFormVisible: false, //开启或者关闭dialog
      //添加的数据
      trademarkInfo: {
        tmName: "",
        logoUrl: "",
      },
      formLabelWidth: "120px",
      rules: {
        //文本校验规则
        tmName: [
          { required: true, message: "请输入品牌名称", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10个字符",
            trigger: "blur",
          },
        ],
        //logo图片校验规则
        logoUrl: [
          { required: true, message: "请选择品牌的图片", trigger: "change" },
        ],
      }, //表单校验
    };
  },
  //挂载完毕就调用，获取品牌数据
  mounted() {
    this.getTrademark();
  },
  methods: {
    // 1. 获取品牌数据列表
    async getTrademark() {
      const { currentPage, pageSize } = this;
      const result = await this.$API.trademark.reqTrademarkList(
        currentPage,
        pageSize
      );
      if (result.code === 200) {
        this.total = result.data.total;
        this.trademarkList = result.data.records;
        this.loading = false; //去掉loading效果
      }
    },

    // 2. 单击页码实现分页效果
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.getTrademark();
    },

    // 3. 修改每页显示数量
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.currentPage = 1; //默认跳转到第一页
      this.getTrademark();
    },

    // 4. 图片上传前的校验
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 5. 图片上传成功后实现预览并获取
    handleAvatarSuccess(res, file) {
      if (res.code !== 200) {
        return $message.error("上传图片失败！");
      }
      // this.logoUrl = URL.createObjectURL(file.raw);
      console.log(res, file);
      this.trademarkInfo.logoUrl = res.data;
      //清除图片校验提示
      this.$refs.ruleForm.clearValidate(this.rules.logoUrl);
    },

    // 6. 点击编辑
    toEditTrademarkInfo(row) {
      this.dialogFormVisible = true;
      console.log(row);
      this.trademarkInfo = { ...row };
      //清除所有校验提示
      /* this.$refs.ruleForm.clearValidate(this.rules) */
    },

    // 7. 点击确定按钮添加品牌或编辑品牌
    addTrademark() {
      this.$refs.ruleForm.validate(async (success) => {
        if (success) {
          //操作成功后关闭对话框
          this.dialogFormVisible = false;

          if (!this.trademarkInfo.id) {
            //弹出信息：添加品牌，修改品牌
            await this.$API.trademark.reqAddTrademark(this.trademarkInfo);
            this.$message.success("添加品牌成功");
            this.currentPage = 1;
          } else {
            await this.$API.trademark.reqEditTrademark(this.trademarkInfo);
            this.$message.success("修改品牌成功");
          }
        } else {
          this.$message(this.trademarkInfo.id ? "修改品牌失败" : "添加品牌失败");
          return false;
        }
        // 重新获取数据
        this.getTrademark();
      });
    },

    //8, 单击添加时，弹出对话框，同时要清空之前的数据
    showTrademarkDialog() {
      this.dialogFormVisible = true;
      this.trademarkInfo = {};
    },

    // 9. 完成删除操作
    toRemoveTrademarkInfo(row) {
      this.$confirm(`您确定要删除${row.tmName}品牌吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          await this.$API.trademark.reqDelTrademark(row.id);
          console.log(row.id);
          this.$message({
            type: "success",
            message: `删除品牌成功了......`,
          });
          this.getTrademark();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除...",
          });
        });
      // 重新获取数据
      this.getTrademark();
    },
  },
};
</script>

<style>
/* .box-card {
  padding: 20px;
} */
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
